package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {

    @Autowired
    DtsPermissionMapper permissionMapper;

    @Override
    public Set<String> findPermsByRoleIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DtsPermission::getRoleId, roleIds);
        wrapper.eq(DtsPermission::getDeleted, false);


        List<DtsPermission> permissionList = permissionMapper.selectList(wrapper);

        Set<String> perms = permissionList.stream().map((permission) -> {
            return permission.getPermission();
        }).collect(Collectors.toSet());

        return perms;
    }

    @Override
    public void updatePermissions(Integer roleId, ArrayList<String> permissions) {
//删除该角色所有的权限
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId, roleId);
        permissionMapper.delete(wrapper);

        //添加新的关系
        if(permissions != null && permissions.size() > 0){
            for (String permission : permissions) {
                DtsPermission perm = new DtsPermission();
                perm.setPermission(permission);
                perm.setRoleId(roleId);
                perm.setAddTime(new Date());
                perm.setDeleted(false);
                perm.setUpdateTime(new Date());

                permissionMapper.insert(perm);
            }
        }
    }
}
